<template>
  <div class="main_box">
    <div class="add_wrap">
      <div class="tit">
        <h2>基础信息</h2>
        <el-button
          plain
          size="small"
          type="success"
          icon="fa fa-mail-forward"
          @click="returnList"
        >
          返 回</el-button
        >
      </div>
      <el-form
        :model="instituForm"
        ref="instituForm"
        label-width="200px"
        :rules="roleRules"
      >
        <el-row>
          <el-form-item label="医检名称" prop="institutionName">
            <el-input v-model.trim="instituForm.institutionName"></el-input>
          </el-form-item>
          <el-form-item label="医检类型" prop="institutionType">
            <el-select
              v-model.trim="instituForm.institutionType"
              placeholder="请选择医检类型"
            >
              <el-option
                v-for="item in institutionTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="医检简称" prop="institutionShortName">
            <el-input
              v-model.trim="instituForm.institutionShortName"
            ></el-input>
          </el-form-item>
          <!--<el-form-item label="机构类型" prop="classifyId">
          <ClassifyRegion :classifyValues="instituForm.classifyId" @classifyRegionChange="handleClassifyChange"></ClassifyRegion>
        </el-form-item>-->
        </el-row>

        <el-row>
          <el-form-item label="所在地区" prop="areaIds">
            <Region
              :areaValues="instituForm.areaIds"
              @regionChange="handleItemChange"
            ></Region>
          </el-form-item>
          <!--<el-form-item label="所在商圈" prop="tradeAreaId">
          <el-select v-model="instituForm.tradeAreaId" @change="tradeChange" placeholder="请选择所在商圈">
            <el-option v-for="item in tradeArea" :label="item.tradeAreaName" :value="item.trId" :key="item.trId"></el-option>
          </el-select>
        </el-form-item>-->

          <el-form-item label="详细地址" prop="institutionAddress">
            <!-- class="location_item"-->
            <el-col>
              <!--:span="11"-->
              <el-input
                v-model.trim="instituForm.institutionAddress"
              ></el-input>
            </el-col>
            <!--<el-col :span="1">&nbsp;</el-col>-->
          </el-form-item>

          <!--<el-form-item
          label="合作医院(可多选)"
          prop="hospitalIds"
        >
          <el-select
            v-model="instituForm.hospitalIds"
            filterable
            clearable
            reserve-keyword
            :loading="loadingIns"
            placeholder="请选择合作医院"
            multiple
            :filter-method="listHospital"
            @focus="listHospital"
          >
            <el-option
              v-for="item in pickHospitalList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>-->
          <el-form-item label="打印机编号" prop="printerCode">
            <el-input v-model.trim="instituForm.printerCode"></el-input>
          </el-form-item>
          <el-form-item label="医检介绍" prop="institutionIntroduce">
            <el-input
              type="textarea"
              v-model.trim="instituForm.institutionIntroduce"
            ></el-input>
          </el-form-item>
        </el-row>

        <el-row>
          <el-form-item label="联系人姓名" prop="contactsName">
            <el-input v-model.trim="instituForm.contactsName"></el-input>
          </el-form-item>
          <el-form-item label="联系人职称" prop="contactsTitle">
            <el-input v-model.trim="instituForm.contactsTitle"></el-input>
          </el-form-item>
          <el-form-item label="联系人手机号" prop="contactsTel">
            <el-input
              v-model.trim="instituForm.contactsTel"
              @change="changeTel"
            ></el-input>
          </el-form-item>
          <el-form-item label="联系人邮箱" prop="contactsEmail">
            <el-input
              v-model.trim="instituForm.contactsEmail"
              @change="changeEmail"
            ></el-input>
          </el-form-item>
        </el-row>

        <el-row>
          <el-form-item>
            <el-button
              plain
              type="primary"
              :disabled="disabledBtn"
              @click="sureInstituClick"
              >保 存</el-button
            >
            <el-button @click="returnList">取 消</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
import InstitutionApi from "@/api/institution/institution";
import * as message from "@/constants/message";
import Region from "@/components/Region";
import HospitalApi from "@/api/institution/hospital";
import { getLocalStorage } from "@/utils/auth";
import * as stn from "@/constants/storeName";

export default {
  data() {
    return {
      instituForm: {
        institutionId: "",
        institutionName: "",
        institutionShortName: "",
        areaIds: [],
        provinceId: "",
        cityId: "",
        areaId: "",
        provinceName: "",
        cityName: "",
        areaName: "",
        hospitalIds: [],
        institutionAddress: "",
        institutionIntroduce: "",
        institutionImageUrl: "",
        contactsName: "",
        contactsTel: "",
        contactsTitle: "",
        contactsEmail: "",
        printerCode: "",
        institutionType: "",
        institutionRelation: ""
      },
      disabledBtn: false,
      loadingIns: false,
      tradeArea: [],
      pickHospitalList: [],
      props: {
        value: "areaId",
        label: "areaName"
      },
      instituClassify: [],
      //1.医检机构 2.三甲机构
      institutionTypeList: [
        { label: "医检机构", value: 1 },
        { label: "三甲机构", value: 2 }
      ],
      roleRules: {
        institutionName: [
          { required: true, message: "请输入医检名称", trigger: "blur" },
          { max: 30, message: "长度不超过30个字", trigger: "blur" }
        ],
        institutionShortName: [
          { required: true, message: "请输入医检简称", trigger: "blur" },
          { max: 20, message: "长度不超过20个字", trigger: "blur" }
        ],
        institutionType: [
          { required: true, message: "请选择医检类型", trigger: "change" }
        ],
        areaIds: [
          { required: true, message: "请选择所在区", trigger: "change" }
        ],
        institutionAddress: [
          { required: true, message: "请输入详细地址", trigger: "blur" }
        ],
        contactsName: [
          { required: true, message: "请输入联系人姓名", trigger: "blur" },
          { max: 15, message: "长度不超过30个字", trigger: "blur" }
        ],
        contactsTitle: [
          { required: true, message: "请输入联系人职称", trigger: "blur" },
          { max: 15, message: "长度不超过30个字", trigger: "blur" }
        ],
        contactsTel: [
          { validator: this.$Utils.elIsPhone, trigger: "blur", required: true }
        ]
      }
    };
  },
  components: {
    Region
  },
  methods: {
    init() {
      if (this.$route.query.id) {
        this.getData();
      }
    },
    handleFile(id, data) {
      const $target = document.getElementById(id);
      const _this = this;
      const file = $target.files[0];
      if (!this.beforeAvatarUpload(file)) {
        return;
      }
      InstitutionApi.getAliyun().then(res => {
        let OSS = require("ali-oss");
        let client = new OSS({
          region: _this.$Config.oss.region,
          accessKeyId: res.data.accessKeyId,
          accessKeySecret: res.data.accessKeySecret,
          stsToken: res.data.securityToken,
          bucket: _this.$Config.oss.bucket
        });
        const fileName = file.name;
        const fileType = fileName.split("\.")[1];
        let fileTempName = new Date().getTime() + fileName.split("\.")[0];
        if (fileTempName.length > 5) {
          fileTempName = fileTempName.substring(0, 12);
        }
        const newName = fileTempName + "." + fileType;
        const storeAs = "web_images/Customer/" + newName;
        const resultUpload = "";
        client
          .put(storeAs, file, {})
          .then(function(r1) {
            let realUrl = r1.url.replace(
              "cactus-pro.oss-cn-hangzhou.aliyuncs.com",
              "image.vvhuimei.com"
            );
            _this.addForm[data] = realUrl;
          })
          .catch(function(err) {
            console.error(err);
          });
      });
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isBMP = file.type === "image/bmp";
      const isLt2M = file.size / 1024 / 1024 < 5;

      if (!isJPG && !isPNG && !isBMP) {
        this.$message.error("上传图片只能是 JPG , PNG , BMP 格式!");
      }

      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 5MB!");
      }
      return (isJPG || isPNG || isBMP) && isLt2M;
    },
    getData() {
      InstitutionApi.getInstitution({
        institutionId: this.$route.query.id
      }).then(res => {
        this.$Utils.bindingBean(this.instituForm, res.data);
        this.instituForm.areaIds = [
          this.instituForm.provinceId,
          this.instituForm.cityId,
          this.instituForm.areaId
        ];
        this.instituForm.institutionType = parseInt(
          this.instituForm.institutionType
        );
        if (this.instituForm.institutionRelation) {
          this.instituForm.hospitalIds = this.instituForm.institutionRelation.split(
            ","
          );
          this.instituForm.hospitalIds = this.instituForm.hospitalIds.map(
            Number
          );
        }
      });
    },
    changeTel(val) {
      // 联系人手机号号码 校验合法性
      if (this.$Utils.isMobile(val)) {
        this.disabledBtn = false;
      } else {
        this.$Utils.messageError("手机号码格式错误");
        this.disabledBtn = true;
      }
      // console.log(val)
      // console.log(this.$Utils.isMobile(val))
    },
    changeEmail(val) {
      // 联系人手机号号码 校验合法性
      if (this.$Utils.isEmptyObject(val)) {
        this.disabledBtn = false;
      } else {
        if (this.$Utils.isEmail(val)) {
          this.disabledBtn = false;
        } else {
          this.$Utils.messageError("邮箱格式错误");
          this.disabledBtn = true;
        }
      }
    },
    sureInstituClick() {
      this.$refs.instituForm.validate(valid => {
        if (valid) {
          this.$confirm(
            message.MSG_CONFIRM_SAVE_ALTER,
            message.TITLE_PROMPT,
            {}
          ).then(() => {
            if (this.instituForm.institutionId) {
              this.editInstitu();
            } else {
              this.addInstitu();
            }
          });
        }
      });
    },
    addInstitu() {
      if (
        this.instituForm.hospitalIds &&
        this.instituForm.hospitalIds.length > 0
      ) {
        this.instituForm.institutionRelation = this.instituForm.hospitalIds.toString();
      }
      let instituData = {
        institutionName: this.instituForm.institutionName,
        institutionShortName: this.instituForm.institutionShortName,
        institutionType: this.instituForm.institutionType,
        institutionRelation: this.instituForm.institutionRelation,
        provinceId: this.instituForm.provinceId,
        cityId: this.instituForm.cityId,
        areaId: this.instituForm.areaId,
        provinceName: this.instituForm.provinceName,
        cityName: this.instituForm.cityName,
        areaName: this.instituForm.areaName,
        institutionAddress: this.instituForm.institutionAddress,
        institutionIntroduce: this.instituForm.institutionIntroduce,
        institutionImageUrl: this.instituForm.institutionImageUrl,
        contactsName: this.instituForm.contactsName,
        contactsTel: this.instituForm.contactsTel,
        contactsTitle: this.instituForm.contactsTitle,
        printerCode: this.instituForm.printerCode,
        contactsEmail: this.instituForm.contactsEmail
      };
      InstitutionApi.addInstitution(instituData).then(data => {
        this.$Utils.notifySuccess();
        this.returnList();
      });
    },
    editInstitu() {
      if (
        this.instituForm.hospitalIds &&
        this.instituForm.hospitalIds.length > 0
      ) {
        this.instituForm.institutionRelation = this.instituForm.hospitalIds.toString();
      }
      let instituData = {
        institutionId: this.$route.query.id,
        institutionName: this.instituForm.institutionName,
        institutionShortName: this.instituForm.institutionShortName,
        institutionRelation: this.instituForm.institutionRelation,
        provinceId: this.instituForm.provinceId,
        cityId: this.instituForm.cityId,
        areaId: this.instituForm.areaId,
        provinceName: this.instituForm.provinceName,
        cityName: this.instituForm.cityName,
        areaName: this.instituForm.areaName,
        institutionAddress: this.instituForm.institutionAddress,
        institutionIntroduce: this.instituForm.institutionIntroduce,
        institutionImageUrl: this.instituForm.institutionImageUrl,
        contactsName: this.instituForm.contactsName,
        contactsTel: this.instituForm.contactsTel,
        contactsTitle: this.instituForm.contactsTitle,
        contactsEmail: this.instituForm.contactsEmail,
        printerCode: this.instituForm.printerCode,
        institutionType: this.instituForm.institutionType
      };
      InstitutionApi.editInstitution(instituData).then(data => {
        this.$Utils.notifySuccess();
        this.returnList();
      });
    },
    cancelInstituClick() {
      this.returnList();
    },
    listHospital() {
      let _this = this;
      _this.loadingIns = true;
      let cond = {
        hospitalType: 1
      };
      HospitalApi.getHospitalNameList(cond)
        .then(res => {
          setTimeout(() => {
            _this.loadingIns = false;
            _this.pickHospitalList = res.data.map(item => {
              return {
                value: item.hospitalId,
                label: item.hospitalName
              };
            });
          }, 200);
        })
        .catch(error => {
          _this.pickHospitalList = [];
          console.error(error);
        });
    },
    handleItemChange(val) {
      this.instituForm.provinceId = val.provinceId;
      this.instituForm.provinceName = val.provinceName;
      this.instituForm.cityId = val.cityId;
      this.instituForm.cityName = val.cityName;
      this.instituForm.areaId = val.areaId;
      this.instituForm.areaName = val.areaName;
      this.instituForm.areaIds = [val.provinceId, val.cityId, val.areaId];
    },
    returnList() {
      this.$store.dispatch("delView", this.$route);
      this.$router.push("/institu/instituManagement");
      //this.$router.go(-1)
      /*let params = getLocalStorage(stn.INSTITU_MANAGEMENT_PARAM)
      if (params){
        this.$router.push({path:'/institu/instituManagement',query:{paramData:params}});
      }else{
        this.$router.push('/institu/instituManagement');
      }*/
    }
  },
  mounted() {
    this.init();
  }
};
</script>
<style lang="scss" src="@/assets/css/views/add.scss" scope></style>
<style scoped>
.add_wrap {
  padding-top: 10px;
  padding-left: 23px;
}
.main_box {
  padding: 10px;
}
</style>
